<?php


namespace app\common\lib\sms;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\facade\Log;

class AliSms
{
    public static function sendSms(string $phone, $code)
    {

        AlibabaCloud::accessKeyClient(config('aliyun.access_key_id'), config('aliyun.access_key_secret'))
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host(config('aliyun.host'))
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $phone,
                        'SignName' => config('aliyun.SignName'),
                        'TemplateCode' => config('aliyun.TemplateCode'),
                        'TemplateParam' => json_encode(['code' => $code]),
                    ],
                ])
                ->request();


            Log::info('alisms-sendCode-' . $phone . 'result' . json_encode($result->toArray()));

            return true;

        } catch (ClientException $e) {
            Log::error('alisms-sendCode-' . $phone . 'ClientException' . $e->getMessage());
            return false;
//            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            Log::error('alisms-sendCode-' . $phone . 'ServerException' . $e->getMessage());
            return false;
//            echo $e->getErrorMessage() . PHP_EOL;
        }
    }
}